package com.snail.snailvr.views;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.snail.snailvr.R;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.event.NewPcConnectEvent;
import com.snail.snailvr.model.VideoInfo;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.DialogUtils;
import com.snail.snailvr.utils.IntentUtils;
import com.snail.snailvr.utils.LogUtils;
import com.snail.snailvr.utils.NetworkUtil;
import com.snail.snailvr.utils.ToastUtils;
import com.snail.snailvr.views.adapter.ClientListAdapter;
import com.snail.snailvr.widget.WrapContentLinearLayoutManager;
import com.squareup.otto.Subscribe;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Observable;
import rx.SingleSubscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static com.snail.snailvr.R.string.use_hint;
import static com.snail.snailvr.R.string.wifi;

public class WiFiActivity extends BaseToolbarActivity implements View.OnClickListener {
    @Bind(R.id.toolbar)
    public Toolbar mToolbar;
    @Bind(R.id.url_to_connect)
    TextView ipAddress;
    @Bind(R.id.use_hint)
    TextView useHint;
    @Bind(R.id.wifi_state)
    TextView wifiState;
    @Bind(R.id.new_video_hint)
    TextView new_video_hint;
    @Bind(R.id.wifi_hint_icon)
    ImageView hint_icon;
    @Bind(R.id.client_list)
    RecyclerView mRecyclerView;
    @Bind(R.id.disconnect)
    TextView disconnect;
    @Bind(R.id.hintPanel)
    View hintPanel;
    @Bind(R.id.contentPanel)
    View contentPanel;

    private boolean wifiTransferServerAlive;
    ClientListAdapter mAdapter;
    private ArrayList<String> mClientLists;
    private Subscription getConnectPcSubscribtion;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_wifi_transfer;
    }

    @Override
    protected void initView() {
        setupToolbar(mToolbar, getString(R.string.wifi_transfer), -1);
        mClientLists = new ArrayList<>(4);
        mAdapter = new ClientListAdapter(this, mClientLists);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(this));
        disconnect.setOnClickListener(this);
        initViewBelongWifiState();
        IntentUtils.startWifiTransferServer(this);
        initConnectPcLists();
    }

    private void initConnectPcLists() {
        getConnectPcSubscribtion=DatabaseUtils.getConnectPcLists(new SingleSubscriber<List<String>>() {
            @Override
            public void onSuccess(List<String> lists) {
                wifiTransferServerAlive=true;
                showConnectedPcList();
                mClientLists.addAll(lists);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable error) {
                LogUtils.d("error="+error.toString());
            }
        });
    }

    @Override
    protected void handleIntent() {

    }

    View.OnClickListener disconnect_listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            IntentUtils.stopWifiTransferServer(WiFiActivity.this);
            finish();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.disconnect:
                DialogUtils.showBasicDialog(this, getString(R.string.Disconnect), getString(R.string.transmittal_disturb),
                        getString(R.string.CANCEL), getString(R.string.dis_connect), true, disconnect_listener);
                break;

            default:
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusProvider.getInstance().register(this);
    }


    @Subscribe
    public void onNewPcConnected(NewPcConnectEvent event) {
        filterAndShow(event);
        // 显示新视频提示&相关处理
        showConnectedPcList();
    }

    private void showConnectedPcList() {
        LogUtils.d("visibility="+contentPanel.getVisibility());
        if (contentPanel.getVisibility() != View.VISIBLE) {
            contentPanel.setVisibility(View.VISIBLE);
            wifiState.setVisibility(View.GONE);
            useHint.setVisibility(View.GONE);
            ipAddress.setVisibility(View.GONE);
            hint_icon.setImageResource(R.drawable.ic_wifi_green);
        }
    }

    /**
     * 过滤重复hostname
     *
     * @param event
     */
    private void filterAndShow(NewPcConnectEvent event) {
        Observable.just(event.getPcName()).filter(new Func1<String, Boolean>() {
            @Override
            public Boolean call(String s) {
                for (String name : mClientLists) {
                    if (name.equals(s))
                        return false;
                }
                return true;
            }
        }).subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        mClientLists.add(s);
                        mAdapter.notifyItemInserted(mAdapter.getItemCount() - 1);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        BusProvider.getInstance().unregister(this);
        if(getConnectPcSubscribtion!=null&&!getConnectPcSubscribtion.isUnsubscribed())
            getConnectPcSubscribtion.unsubscribe();
    }

    public static Intent getIntent(Context source) {
        Intent intent = new Intent(source, WiFiActivity.class);
        return intent;
    }


    @Subscribe
    public void showNewVideoToast(VideoInfo videoInfo) {
        ToastUtils.makeToastColorShow(this, new_video_hint, getResources().getString(R.string.new_video));
    }

    @Override
    protected boolean onToolbarMenuItemClick(MenuItem item) {
        return false;
    }


    private void initViewBelongWifiState() {

        if (NetworkUtil.isWifiConnected()) {
            // 连接
            wifiConnected();
        } else {
            wifiDisconnected();

        }
    }

    @Override
    protected void wifiDisconnected() {
        super.wifiDisconnected();
        LogUtils.d("wifiDisconnected");
        // 断开
        ipAddress.setVisibility(View.GONE);
        useHint.setVisibility(View.VISIBLE);
        useHint.setText(getString(R.string.wifi_hint));
        contentPanel.setVisibility(View.GONE);
        wifiState.setVisibility(View.VISIBLE);
        wifiState.setText(getString(R.string.wifi_disable));
        hint_icon.setImageResource(R.drawable.ic_wifi_yellow);
        hintPanel.setVisibility(View.VISIBLE);
    }

    @Override
    protected void wifiConnected() {
        super.wifiConnected();

        if(!wifiTransferServerAlive) {
            String ip = NetworkUtil.getIpAddress();
            this.ipAddress.setText(String.format(getString(R.string.ip), ip));
            this.ipAddress.setVisibility(View.VISIBLE);
            useHint.setVisibility(View.VISIBLE);
            useHint.setText(String.format(getString(use_hint), NetworkUtil.getWifiName(this)));
            contentPanel.setVisibility(View.GONE);
            wifiState.setVisibility(View.VISIBLE);
            wifiState.setText(String.format(getString(wifi), NetworkUtil.getWifiName(this)));
            hint_icon.setImageResource(R.drawable.ic_wifi_blue);
        }
    }



    public void onResume() {
        super.onResume();

    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}